token='51b6a0ca6ba89e6b5f6560c475c5e2ec'


import time
 
host='localhost'
database='my_application'
user='root'
password='Root1234567'
token_lifetime=2592000

# 数据库连接 pip install mysql-connector-python
import mysql.connector
from mysql.connector import Error
def connect_mysql_db():
    try:       
        connection = mysql.connector.connect(host=host,database=database, user=user, password=password)
        if connection.is_connected():
            print("连接成功！")
            return connection
    except Error as e:
        print(f"连接失败：{e}")
    return None

def excute(connection, query):
    cursor = None
    if connection is not None:
        cursor = connection.cursor(dictionary=True)
        cursor.execute(query)
    return cursor

def find_first(connection,sql):
    result = None
    cursor = excute(connection, sql)
    if cursor:
        print("查询一条数据：")
        result = cursor.fetchone()
        
        print(result)

    return result
# 查询select
def find(connection, query):
    result = None
    cursor = excute(connection,query)
    if cursor:
        print("查询数据：")
        result = cursor.fetchall()
        
        for row in result:
            print(row)

    return result

def save(connection,sql):
    if connection is not None:
        cursor = connection.cursor(dictionary=True)
        cursor.execute(query)
    pass
    

    

#  检测token有效性
def check_token(token):
    user = None
    connection = connect_mysql_db()
    if connection:
       
        query = f'select * from token where token="{token}"  '
        print(query)
        result = find_first(connection, query)
         
        if result:
            ex = int(time.time()) + token_lifetime
            id = result['token_id']
            sql = f'update token set expired_at={ex} where token_id={id}'
            print(sql)
            excute(connection,query=sql)
            find_first(connection, query)
            # 获取用户信息and expired_at > {expired_at}
            user = {
                'user_id'    : result['user_id'],
                'token_type' : result['token_type']
            }
            

            return user        
        connection.close()
    return user
token = 'ae7959dfa37b2989eda36ab977752c2c'
check_token(token)
# if check_token(token) :
#     print('查询到有结果')
# else:
#     print('没有查询到结果')

        
        